package com.hais1992.oneday.tools;

public class StringUtil {

	/**
	 * Java按字节数截取字符串，一个中文长度为2
	 * 
	 * @param str
	 *            要截取的字符串
	 * @param subLength
	 *            截取字节数
	 * @return
	 */
	public static String limitString(String str, int subLength) {
		try {
			if (str == null) {
				return "";
			} else {
				int tempSubLength = subLength;//
				String subStr = str.substring(0,
						str.length() < subLength ? str.length() : subLength);
				int subByetsLength = subStr.getBytes("GBK").length;// 截取子串的字节长度
				// 说明截取的字符串中包含有汉字
				while (subByetsLength > tempSubLength) {
					int subLengthTemp = --subLength;
					subStr = str.substring(0,
							(subLengthTemp > str.length() ? str.length()
									: subLengthTemp));
					subByetsLength = subStr.getBytes("GBK").length;
				}
				return subStr;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
}
